<template>
  <div class="search-box">
    <el-autocomplete
        v-model="keyword"
        :fetch-suggestions="handleSearch"
        :trigger-on-focus="true"
        clearable
        placeholder="输入城市+关键字搜索"
        @select="handleSelect"
    />
    <!-- 新增：绑定点击事件 -->
    <el-button :icon="LocationFilled" style="margin-top: 5px" type="primary" plain @click="getMyPosition">我的位置</el-button>
    <!-- 新增：导航按钮 -->
    <el-button style="margin-top: 5px" type="success" plain @click="navigateToDestination">导航</el-button>
  </div>
  <div id="container"></div>
  <!-- 新增：导航路线详情面板 -->
  <div id="my-panel" style="width: 360px; height: 500px; overflow: auto;"></div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import {
  LocationFilled
} from '@element-plus/icons-vue'
let map = null;
const keyword = ref("");
const myLocation=ref({
  lng:null, //精度
  lat:null
});

//路线规划
const startPoint=ref({
  lng:null, //精度
  lat:null});
const endPoint=ref({
  lng:null, //精度
  lat:null
});

// 新增：提取公共方法
const showMessage = (type, message) => {
  ElMessage[type](message);
};

// 修改：优化 getMyPosition 方法
const getMyPosition = () => {
  if (!map) {
    showMessage("warning", "地图尚未加载，请稍后再试");
    return;
  }
  const geolocation = new AMap.Geolocation({
    enableHighAccuracy: true,
    timeout: 10000,
    buttonPosition: "RB",
    buttonOffset: new AMap.Pixel(10, 20),
    zoomToAccuracy: true,
  });
  map.addControl(geolocation);
  geolocation.getCurrentPosition((status, result) => {
    if (status === "complete") {
      const { position } = result;
      showMessage("success", `定位成功: 经度 ${position.lng}, 纬度 ${position.lat}`);
      map.setCenter(position);
      myLocation.value={
        lng:position.lng,
        lat:position.lat
      };
    } else {
      showMessage("error", "定位失败，请检查定位权限");
    }
  });
};

// 修改：优化 navigateToDestination 方法
const navigateToDestination = () => {
  if (!startPoint.value.lng || !startPoint.value.lat || !endPoint.value.lng || !endPoint.value.lat) {
    showMessage("warning", "请先设置起点和终点");
    return;
  }
  const startLngLat = [startPoint.value.lng, startPoint.value.lat];
  const endLngLat = [endPoint.value.lng, endPoint.value.lat];

  AMap.plugin(["AMap.Driving"], function () {
    const driving = new AMap.Driving({
      map: map,
      panel: "my-panel",
    });
    driving.search(startLngLat, endLngLat, function (status, result) {
      if (status === "complete") {
        showMessage("success", "导航路线规划成功");
      } else {
        showMessage("error", "导航路线规划失败");
      }
    });
  });
};

// 新增：搜索建议方法
const handleSearch = (queryString, cb) => {
  if (!queryString) {
    cb([]);
    return;
  }
  const placeSearch = new AMap.PlaceSearch({
    city: "全国",
    map: map,
  });
  placeSearch.search(queryString, (status, result) => {
    if (status === "complete" && result.info === "OK") {
      const suggestions = result.poiList.pois.map((poi) => ({
        value: poi.name,
        address: poi.address,
        location: poi.location,
      }));
      cb(suggestions);
    } else {
      cb([]);
      ElMessage.warning("未找到相关地点");
    }
  });
};

// 新增：处理搜索结果选择
const handleSelect = (item) => {
  if (item.location) {
    map.setCenter(item.location);
    map.setZoom(15);
  }
};

const getAllMerchantsInfo = async () => {
  const res = await request.get("/api/merchant/list");
  return res.data;
};

// 修改：优化 openInfo 方法
const openInfo = (merchant) => {
  const content = `
    <div style="
      min-width: 250px;
      padding: 15px;
      font-family: 'Helvetica Neue', Arial, sans-serif;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      color: #333;
    ">
      <div style="
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        padding-bottom: 8px;
        border-bottom: 1px solid #eee;
      ">
        <img src="http://47.109.143.177:9001/mystorge/%E5%B0%8F%E5%8D%96%E9%83%A8%E5%95%86%E5%BA%97%E7%BC%A9%E5%B0%8F.png"
             style="width: 40px; height: 40px; margin-right: 10px;">
        <h3 style="
          margin: 0;
          font-size: 18px;
          color: #1890ff;
          font-weight: 600;
        ">${merchant.name}</h3>
      </div>

      <div style="margin-bottom: 8px;">
        <span style="
          display: inline-block;
          width: 60px;
          color: #888;
        ">电话</span>
        <span>${merchant.contactPhone || '暂无'}</span>
      </div>

      <div style="margin-bottom: 8px;">
        <span style="
          display: inline-block;
          width: 60px;
          color: #888;
        ">地址</span>
        <span>${merchant.address}</span>
      </div>

      <div>
        <span style="
          display: inline-block;
          width: 60px;
          color: #888;
        ">描述</span>
        <span style="color: #666;">${merchant.description || '暂无描述'}</span>
      </div>

     <button id="navButton" style="padding: 6px 6px;background: #1890ff;color: white;border: none;border-radius: 4px;font-size: 14px;cursor: pointer;transition: all 0.3s;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);">
     设置为目的地
     </button>
    </div>`;
  const infoWindow = new AMap.InfoWindow({
    content: content,
    anchor: "bottom-center",
    offset: new AMap.Pixel(0, -30),
    closeWhenClickMap: true,
  });
  const position = new AMap.LngLat(merchant.longitude, merchant.latitude);
  infoWindow.open(map, position);

  // 直接在 Vue 模板中绑定事件
  const button = document.getElementById("navButton");
  if (button) {
    button.addEventListener("click", () => {
      go(merchant);
    });
  }
};

const go = (destination) => {
  if(myLocation.value.lng===undefined||myLocation.value.lat===undefined||myLocation.value.lng===null||myLocation.value.lat===null){
    ElMessage.warning("请先获取当前定位");
    return
  }
  if(destination.longitude&&destination.latitude){
    startPoint.value = {
      lng: myLocation.value.lng,
      lat: myLocation.value.lat
    };
    endPoint.value = {
      lng: destination.longitude,
      lat: destination.latitude
    };
    ElMessage.success("获取目的地经纬度成功");
  }
};

onMounted(async () => {
  let merchantList = [];
  merchantList = await getAllMerchantsInfo();
  console.log("merchantList is ", merchantList);

  window._AMapSecurityConfig = {
    securityJsCode: "053bcdbeb7a3a866824048eb560f86ba",
  };
  AMapLoader.load({
    key: "115064a6aa3abdbf40d8970790081bb9",
    version: "2.0",
    resizeEnable: true,
  }).then((AMap) => {
    map = new AMap.Map("container", {
      viewMode: "3D",
      zoom: 7,
      center: [102.397428, 31.90923],
    });
    AMap.plugin(
        [
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.HawkEye',
          'AMap.Geolocation',
          "AMap.PlaceSearch"
        ],
        function () {
          const scale = new AMap.Scale();

          const controlBar = new AMap.ToolBar({
            position: {
              top: '110px',
              right: '40px',
            },
          });
          const overview = new AMap.HawkEye({
            opened: false,
          });

          // map.addControl(new AMap.ToolBar());
          map.addControl(scale);
          map.addControl(overview);

          function toggleScale(checkbox) {
            if (checkbox.checked) {
              scale.show()
            } else {
              scale.hide()
            }
          }

          function toggleBar(checkbox) {
            if (checkbox.checked) {
              controlBar.show()
            } else {
              controlBar.hide()
            }
          }

          function toggleOverview(checkbox) {
            if (checkbox.checked) {
              overview.show()
            } else {
              checkbox.hide()
            }
          }
        }
    );

    merchantList.forEach((merchant) => {
      console.log("读取的 merchant is ", merchant)
      const markerContent =
          `<div class="custom-content-marker" style="display: flex;flex-direction: column;align-items: center;justify-content: center">
        <img src="http://47.109.143.177:9001/mystorge/%E5%B0%8F%E5%8D%96%E9%83%A8%E5%95%86%E5%BA%97%E7%BC%A9%E5%B0%8F.png">
        <p style="color: red;width: 80px;font-size: 13px;font-weight: bold;text-align: center">${merchant.name}</p>

    </div>`;


      const lng = parseFloat(merchant.longitude);
      const lat = parseFloat(merchant.latitude);
      if (isNaN(lng) || isNaN(lat)) {
        console.error('无效坐标:', merchant);
        return;
      }
      if (lng < 73 || lng > 136 || lat < 3 || lat > 54) {
        console.error('坐标超出中国范围:', merchant);
        ElMessage.warning('无效的坐标')
        return;
      }

      const position = new AMap.LngLat(merchant.longitude, merchant.latitude);
      const marker = new AMap.Marker({
        position: position,
        content: markerContent,
        offset: new AMap.Pixel(-13, -30)
      });

      marker.on('click', function (e) {
        openInfo(merchant)
      });
      map.add(marker);
    });

    console.log("map 加载成功", map);
  }).catch((e) => {
    console.log(e);
  });
});

onUnmounted(() => {
  // map.destroy();
});
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
.search-box {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1000;
  background-color: white;
  padding: 5px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
#my-panel{
  position: absolute;
  top: 10px;
  right: 20px;
}
</style>
